

<script setup lang="jsx">
import { ref } from 'vue';
import dayjs from 'dayjs';
import { ElButton } from 'element-plus';
import { useAppStore } from '@/store/modules/app';
import { $t } from '@/locales';
import { fetchGetOrders } from '@/service/api';
import { useTable } from '@/hooks/common/table';
import { localStg } from '@/utils/storage';
import { orderTypeOptions, orderStatusOptions } from '@/constants/common';
import OrderSearch from './modules/order-search.vue';

const appStore = useAppStore();
const activeName = ref(orderTypeOptions[0].value);
const LocalExchange = ref({})

const {
  columns,
  columnChecks,
  data,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchData,
  apiParams: {
    PageIndex: 1,
    PageSize: 30,
    SystemStatus: -1,
    OrderBy: 1,
    SearchType: 1,
    SearchContent: undefined,
    orderTime: undefined,
    settlementStatus: undefined,
  },
  columns: () => [
    { 
      prop: 'PlatformsId', 
      label: $t('page.order.storeName'),
      width: 150,
      formatter: row => {
        const platformMap = {
          0: 'shopee',
          1: 'tiktok',
          2: 'tokopedia',
        }
        return <div class='flex px-10px'>
            <img src={'/src/assets/images/platform/'+platformMap[row.PlatformsId]+'.png'} class='w-40px h-40px' />
            <span class='text-12px'>{row.ShopName}</span>
          </div>
      }
    },
    { 
      prop: 'OrderSN', 
      label: $t('page.order.orderInfo'),
      width: 150,
      formatter: row => {
        return <div class='flex-col'>
            <span>{row.OrderSN}</span>
            <span>{formatDate(row.CreateTime)}</span>
          </div>
      }
    },
    { 
      prop: 'info', 
      label: '商品信息', 
      align: 'left',
      headerAlign: 'center',
      formatter: row =>{
        return row.Items.map((item,index)=><div key="{index}" class="flex">
          <img src={item.ImageList[0]} alt="商品图片" class="w-80px h-80px" />
          <div class="ml-10 flex-col">
            <div class="color-#111827 font-14">{item.ItemName}</div>
            <div class="color-#687280">{item.VariationName}</div>
          </div>
        </div>)
      }
    },
    { prop: 'CreateTime', label: '下单时间', width: 160 },
    { 
      prop: 'price', 
      label: '订单金额', 
      align: 'center',
      width: 140,
      formatter: row => {
        return row.Items.map((item,index)=><div key="{index}">
          { LocalExchange.value.CurrencySymbol } {formatPrice(item.VariationDiscountedPrice, false)}
          <span> * </span>
          <span class="color-#f56c6c">{ item.VariationQuantityPurchased }</span>
        </div>)
      }
    },
    {
      prop: 'OrderStatus',
      label: '订单状态',
      width: 120,
      formatter: row => {
        if (row.OrderStatus === undefined) return ''

        const status = orderStatusOptions.find(item=> item.value === row.OrderStatus)
        const statusText = status ? $t(status.label) : ''

        const tagMap = {
          1: 'warning',
          2: 'primary',
          6: 'danger',
          8: 'success',
        }

        return <ElTag type={tagMap[row.OrderStatus]}>{statusText}</ElTag>;
      }
    },
    {
      prop: 'type',
      label: '发货方式',
      width: 100,
      formatter: row => {
        if (row.status === undefined) return ''

        const typeRecord = {
          1: '自主发货',
          2: '平台发货',
        };

        const tagMap = {
          1: 'warning',
          3: 'success'
        }

        return <ElTag type={tagMap[row.status]}>{typeRecord[row.status]}</ElTag>;
      }
    },
    {
      prop: 'operate',
      label: $t('common.operate'),
      width: 160,
      formatter: row => (
        <div class="flex-center">
          <ElLink underline={false}>申请售后</ElLink>
          <ElLink underline={false}>标记虚拟订单</ElLink>
          <ElLink underline={false} onClick={() => handleView(row.id)}>详情</ElLink>
        </div>
      )
    }
  ]
});

function formatPrice(val, blXS){
  if(val >= 1000000){
    return `${(val / 1000000.0).toFixed(2)}M`
  }else if(val >= 1000){
    return `${(val / 1000.0).toFixed(2)}K`
  }else{
    return blXS ? val.toFixed(2) : `${val}`
  }
}
function formatDate(dateStr){
  console.log('dateStr', dateStr)
  return dayjs(dateStr).format('YYYY/MM/DD HH:mm')
}
function handleExport(){}
function handlePurchase(){}
function handleView(id) {}
function handleClick() {}

async function fetchData(params){
  const res = await appStore.getCurrency()
  const station = localStg.get('station')
  LocalExchange.value = res.find(item => item.CountryCode === station) || {}

  return fetchGetOrders(params)
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <OrderSearch 
      v-model:model="searchParams" 
      @reset="resetSearchParams" 
      @search="getDataByPage"
      @exports="handleExport"
      @purchase="handlePurchase" />

    <ElCard class="sm:flex-1-hidden card-wrapper" body-class="ht50 pt-0">
      <template #header>
        <TableHeaderOperation :loading="loading" @refresh="getData" :show-refresh="false">
          <template #prefix>
            <ElTabs v-model="activeName" @tab-click="handleClick">
              <ElTabPane 
                v-for="item of orderTypeOptions" 
                :key="item.value" 
                :label="$t(item.label)+`(${item.count || 0})`" 
                :name="item.value"></ElTabPane>
            </ElTabs>
          </template>
          <template #default>
            <span></span>
          </template>
        </TableHeaderOperation>
      </template>
      <div class="h-[calc(100%-50px)]">
        <ElTable v-loading="loading" height="100%" border class="sm:h-full" :data="data" row-key="ShopId">
          <ElTableColumn v-for="col in columns" :key="col.prop" v-bind="col" />
        </ElTable>
        <div class="mt-20px flex justify-end">
          <ElPagination
            v-if="mobilePagination.total"
            layout="total,prev,pager,next,sizes"
            v-bind="mobilePagination"
            @current-change="mobilePagination['current-change']"
            @size-change="mobilePagination['size-change']"
          />
        </div>
      </div>
    </ElCard>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-card) {
  .ht50 {
    height: calc(100% - 50px);
  }
}
</style>